#include "Map.h"
#include "Game.h"
#include "Renderer.h"
#include "Audio.h"

#include <SDL/SDL.h>
#include <sys/time.h>

SDL_Surface *screen;

double GetDeltaTime()
{
	static double oldtime=0;

	struct timeval tv;
	gettimeofday(&tv,NULL);
	double time=(double)tv.tv_sec+(double)tv.tv_usec/1000000.0;

	if(!oldtime) { oldtime=time; return 0; }

	double dt=time-oldtime;
	oldtime=time;

	if(dt>0.1) return 0.1;
	return dt;
}

int main(int argc, char **argv)
{
	double t=0;
	double nextloop=0;

	Renderer renderer;
	if(!InitRenderer(&renderer,"paleta")) exit(0);

	Map map;
	if(!LoadMap(&map,"plan")) exit(0);
	if(!PrepareForMap(&renderer,&map)) exit(0);

	Game game;
	StartGame(&game,&map);

	audio_init();
	audio_music(MUS_STARDUST,"MOD.stardust memories");

	for(;;)
	{
		SDL_Event event;
		while(SDL_PollEvent(&event))
		switch(event.type)
		{
			case SDL_QUIT: exit(0);
			case SDL_KEYDOWN:
				switch(event.key.keysym.sym)
				{
					case SDLK_DELETE: RestartGame(&game,&map); break;
					case SDLK_ESCAPE: exit(0);
				}
			break;
		}

		double dt=GetDeltaTime();
		t+=dt;

		unsigned char *key=SDL_GetKeyState(NULL);

		int haschanged=0;
		while(t>nextloop)
		{
			GameLoop(&game,&map,key[SDLK_LEFT],key[SDLK_RIGHT],key[SDLK_UP],key[SDLK_DOWN],
			key[SDLK_LSHIFT]||key[SDLK_RSHIFT],key[SDLK_SPACE]);
			nextloop+=1.0/25.0;
			haschanged=1;
		}

		if(haschanged) Render(&renderer,&map,&game,audio_music_get_row()>>1);
		SDL_Delay(5);
	}

	//free_object(obj);

	return 0;
}

#ifdef _OS_WINDOWS_
#include <windows.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>
extern int __argc;
extern char **__argv;
int WINAPI WinMain(HINSTANCE a,HINSTANCE b,LPSTR c,int d) {
	//AllocConsole();
	//*stdout = *_fdopen(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), 0x4000),"w");
	return main(__argc,__argv);
}
#endif
